package com.lm.controller;

import com.lm.pojo.Message;
import com.lm.pojo.User;
import com.lm.pojo.UserInfo;
import com.lm.service.MessageService;
import com.lm.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 显示聊天页面
     */
    @GetMapping
    public String showChatPage(Model model, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/login";
        }

        // 获取所有聊天对象
        List<String> chatUsers = messageService.getChatUsers(loginUser.getUid());
        
        // 获取每个聊天对象的未读消息数
        Map<String, Integer> unreadCounts = chatUsers.stream()
                .collect(Collectors.toMap(
                        uid -> uid,
                        uid -> messageService.getUnreadCount(loginUser.getUid(), uid)
                ));

        model.addAttribute("chatUsers", chatUsers);
        model.addAttribute("unreadCounts", unreadCounts);
        return "chat/index";
    }

    /**
     * 显示与特定用户的聊天记录
     */
    @GetMapping("/{uid}")
    public String showChatWithUser(@PathVariable String uid, Model model, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/login";
        }

        // 获取聊天记录
        List<Message> messages = messageService.getChatHistory(loginUser.getUid(), uid);
        
        // 获取对方用户信息
        UserInfo otherUserInfo = userInfoService.getUserInfoByUid(uid);
        
        model.addAttribute("messages", messages);
        model.addAttribute("otherUser", otherUserInfo);
        return "chat/chat";
    }

    /**
     * 发送消息
     */
    @PostMapping("/send")
    @ResponseBody
    public String sendMessage(@RequestParam String receiverUid,
                            @RequestParam String content,
                            @RequestParam(defaultValue = "0") Integer msgType,
                            HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "请先登录";
        }

        try {
            messageService.sendMessage(loginUser.getUid(), receiverUid, content, msgType);
            return "success";
        } catch (Exception e) {
            return "发送失败：" + e.getMessage();
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/read/{messageId}")
    @ResponseBody
    public String markAsRead(@PathVariable Integer messageId) {
        try {
            messageService.markAsRead(messageId);
            return "success";
        } catch (Exception e) {
            return "操作失败：" + e.getMessage();
        }
    }

    /**
     * 获取未读消息数
     */
    @GetMapping("/unread/count")
    @ResponseBody
    public int getUnreadCount(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return 0;
        }
        return messageService.getUnreadMessages(loginUser.getUid()).size();
    }
} 